package com.syt.tank.handler;

import java.util.Map;
import java.util.Random;

import org.apache.mina.core.session.IoSession;
import org.springframework.web.bind.annotation.RequestMapping;

import com.syt.mina.handler.SytHandler;
import com.syt.mina.session.ISessionManager;
import com.syt.tank.message.AddPlayerMsg;
import com.syt.tank.message.MessageIds;
import com.syt.tank.message.SendMoveMsg;
import com.syt.tank.message.TankSessionManager;

import flex.messaging.io.amf.ASObject;

@RequestMapping("/player")
public class PlayerHandler extends SytHandler {
	
	@RequestMapping(value="/login")
	public void loginPlayer(IoSession session, ASObject message) {
		String playerId = String.valueOf(session.getId());
		
		AddPlayerMsg msg = new AddPlayerMsg(playerId,playerId);
		msg.setX(100);
		msg.setY(200);
		TankSessionManager manager = (TankSessionManager)getSessionManager();
		manager.updateInfo(playerId, 100, 200, false);
		manager.broadcastMessage(msg);
		
		Map<String,AddPlayerMsg> playerMap = manager.getPlayerMap();
		synchronized (playerMap) {
			for(AddPlayerMsg m : playerMap.values()){
				if(! playerId.equals(m.getPlayerFrom())){
					session.write(m.getMessage());
				}
			}
		}
	}
	
	@RequestMapping(value="/move")
	public void move(IoSession session, ASObject message) {
		String flag = (String)message.get("flag");
		boolean isMove = false;
		if("move".equals(flag)){
			isMove = true;
		}
		
		String playerId = String.valueOf(session.getId());
		SendMoveMsg sd = new SendMoveMsg(playerId,null);
		sd.setAs(message);
		
		TankSessionManager manager = (TankSessionManager)getSessionManager();
		manager.updateInfo(playerId, (Integer)message.get("x"), (Integer)message.get("y"),isMove);
		
		manager.broadcastMessage(sd);
	}
	
	@RequestMapping(value="/fire")
	public void fire(IoSession session, ASObject message) {
		TankSessionManager manager = (TankSessionManager)getSessionManager();
		message.put("msgId", MessageIds.TANK_FIRE_ID);
		manager.broadcastMessageAs(message);
	}
}
